package ge.telasi.tasks.ui.task;

import ge.telasi.tasks.model.Task;
import ge.telasi.tasks.model.TaskReceiver;
import ge.telasi.tasks.ui.Platform;
import ge.telasi.tasks.ui.UIUtils;
import ge.telasi.tasks.ui.comp.SimpleTable;
import ge.telasi.tasks.ui.comp.TableModel;
import ge.telasi.tasks.ui.log.LoggerUtils;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.swing.Icon;
import javax.swing.JTable;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 * @author dimitri
 */
public class TaskTable extends SimpleTable<Task> {
    private static final long serialVersionUID = -7462220491942271965L;
    static final int STATUS      = 0;
    static final int ATTACHMENT  = 1;
    static final int RELATION    = 2;
    static final int NUMBER      = 3;
    static final int DATE        = 4;
    static final int SUBJECT     = 5;
    static final int OWNER       = 6;
    static final int ASSIGNEE    = 7;
    static final int PRIORITY    = 8;
    static final int DUE_DATE    = 9;
    static final int PREPARED_BY = 10;
    static final int STRUCTURE   = 11;
    static final int CANC_NUMBER = 12;

    public TaskTable() {
        super();
        setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        TableColumnModel colModel = getColumnModel();
        TableColumn colStatus = colModel.getColumn(STATUS);
        TableColumn colAttachment = colModel.getColumn(ATTACHMENT);
        TableColumn colRelation = colModel.getColumn(RELATION);
        colStatus.setResizable(false);
        colAttachment.setResizable(false);
        colRelation.setResizable(false);
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evnt) {
                if (evnt.getClickCount() > 1) {
                    openTask();
                }
            }
        });
    }

    @Override
    protected TableModel<Task> createEmptyModel() {
        return new TaskTableModel();
    }

    @Override
    protected List<Task> getDataFromServer(Platform pl) throws Exception {
        throw new UnsupportedOperationException("Refresh not supported.");
    }

    @Override
    protected String getPreferenceName() {
        return "885554411112236";
    }

    @Override
    protected int[] getDefaultColumnWidthes() {
        int[] widthes = { 20, 20, 20, 100, 120, 150, 150, 100, 80, 150, 150, 100 };
        return widthes;
    }

    public void openTask() {
        Task selected = getSelection();
        if (selected != null && Platform.getDefault().validateConnection()) {
            if (selected.getTaskStatus() == Task.STATUS_DRAFT) {
                openDraftTask(selected);
            } else {
                openNonDraftTask(selected);
            }
        }
    }

    private void openDraftTask(final Task baseTask) {
        Platform pl = Platform.getDefault();
        try {
            Task task = pl.getFacade().getTask(pl.getCredentials(), baseTask);
            NewTaskDialog dialog = new NewTaskDialog(this);
            dialog.setTask(task);
            dialog.addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent evt) {
                    if ("task".equals(evt.getPropertyName())) {
                        Task task = (Task) evt.getNewValue();
                        replace(task);
                    }
                }
            });
            UIUtils.openDialog(dialog);
            if (dialog.isApproved()) {
                refresh();
            }
        } catch (Exception ex) {
            LoggerUtils.manageException(this, ex);
        }
    }

    private void openNonDraftTask(final Task baseTask) {
        Platform pl = Platform.getDefault();
        try {
            Task task = pl.getFacade().getTask(pl.getCredentials(), baseTask);
            TaskEditDialog dialog = new TaskEditDialog(this);
            dialog.addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent evt) {
                    if ("task".equals(evt.getPropertyName())) {
                        Task task = (Task) evt.getNewValue();
                        replace(task);
                    }
                }
            });
            dialog.setTask(task);
            UIUtils.openDialog(dialog);
        } catch (Exception ex) {
            LoggerUtils.manageException(this, ex);
        }
    }

    static class TaskTableModel extends TableModel<Task> {
        private static final long serialVersionUID = -558876990782169722L;
        DateFormat df_full = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        DateFormat df_short = new SimpleDateFormat("dd/MM/yyyy");

        @Override
        public int getColumnCount() {
            return 12;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            switch (columnIndex) {
                case STATUS:
                case ATTACHMENT:
                case RELATION:
                    return Icon.class;
                case TaskTable.NUMBER:
                case TaskTable.SUBJECT:
                case TaskTable.OWNER:
                case TaskTable.ASSIGNEE:
                case TaskTable.PRIORITY:
                case TaskTable.DUE_DATE:
                case TaskTable.DATE:
                case TaskTable.PREPARED_BY:
                case TaskTable.STRUCTURE:
                case TaskTable.CANC_NUMBER:
                    return String.class;
                default:
                    return Object.class;
            }
        }

        @Override
        public String getColumnName(int column) {
            switch (column) {
                case STATUS:
                case ATTACHMENT:
                case RELATION:
                    return "";
                case NUMBER:
                    return "ნომერი";
                case SUBJECT:
                    return "სათაური";
                case OWNER:
                    return "მფლობელი";
                case ASSIGNEE:
                    return "შემსრულებელი";
                case PRIORITY:
                    return "პრიორიტეტი";
                case DUE_DATE:
                    return "თარიღამდე";
                case DATE:
                    return "თარიღი";
                case PREPARED_BY:
                    return "მოამზადა";
                case STRUCTURE:
                    return "გამომგზავნი სტრუქტ. ერთეული";
                case CANC_NUMBER:
                    return "კანც. №";
                default:
                    return "?";
            }
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }

        @Override
        public Object getValueAt(int row, int column) {
            Task task = getObjectAt(row);
            return getValue(task, column);
        }

        public Object getValue(Task task, int column) {
            switch (column) {
                case STATUS:
                    return TaskDecontationUtils.getStatusIcon(task);
                case ATTACHMENT:
                    return TaskDecontationUtils.getAttachIcon(task);
                case RELATION:
                    return TaskDecontationUtils.getRelationIcon(task);
                case NUMBER:
                    return task.getNumber();
                case SUBJECT:
                    return task.getSubject();
                case OWNER:
                    return task.getOwner().getFullName();
                case ASSIGNEE:
                    try {
                        List<TaskReceiver> receivers = task.getReceivers();
                        if (receivers.isEmpty()) {
                            return "--";
                        } else {
                            TaskReceiver r = receivers.get(0);
                            for (TaskReceiver rcvr : receivers) {
                                if (!rcvr.isCopy() && rcvr.isActive()) {
                                    r = rcvr;
                                    break;
                                }
                            }
                            if (r.getUser() != null) {
                                return r.getUser().getFullName();
                            } else {
                                return r.getGroup().getName();
                            }
                        }
                    } catch (Exception ex) {
                        return "?";
                    }
                case PRIORITY:
                    return TaskDecontationUtils.getPriorityName(task.getPriority());
                case DUE_DATE:
                    return task.getDueDate() == null ? "--" : df_short.format(task.getDueDate().getTime());
                case DATE:
                    return df_full.format(task.getCreated().getTime());
                case PREPARED_BY:
                    return task.getPreparedBy().getFullName();
                case STRUCTURE:
                    return task.getStructure().getName();
                case CANC_NUMBER:
                    return task.getCancelariaNumber();
                default:
                    return null;
            }
        }

    }

}
